import TWebLive from 'tweblive'
import im from 'tim-js-sdk'

export const mixinChat = {
	data() {
		return {
			im: null,
			msgList: [],
			currentLiveTips: [],
			isIMSDKReady: false,
			isLiveLogin: false,
			showMessage: true,
			tips: [],
			preScrollHeight: 0,
			messageContent: '',
			isSendCustomMessage: false,
			sendCustomDialogVisible: false,
			surveyDialogVisible: false,
			form: {
				data: '',
				description: '',
				extension: ''
			},
			showAtGroupMember: false,
			atUserID: '',
			focus: false,
			sendGiftUser: {
				nick_name: ''
			}, // 送礼人信息
			hasGift: false,
			giftInfo: {},
			giftStack: [],
			giftList: [],
			p: 0, // 在线用户页码
			onlineUser: {},
			onlineUserNum: 0,
			onlineUserLoadingType: 'more',
			likeNum: 0,
		}
	},
	computed: {
		messageQueen: function() {
			const queenLen = 100 //内存里面放100条消息，以免观看直播太久撑爆内存
			if (this.msgList.length > queenLen) {
				const vl = this.msgList.length - queenLen
				for (let i = 0; i < vl; i++) {
					this.msgList.shift()
				}
			}
			return this.msgList
		},
		showTip() {
			if (this.currentLiveTips.length > 0) {
				let msg = this.currentLiveTips[0];
				this.$u.toast(msg.payload.text)
			}
		},
	},
	watch: {},
	updated() {
		//this.keepMessageListOnButtom()
	},
	created() {},
	mounted() {

	},
	methods: {
		initChat() {
			this.initIMListener();
			this.getGift();
			this.getOnlineUser();
			this.getLike();
		},
		initIMListener() {
			let that = this;
			//初始化
			let SDKAppID = this.chatInfo.SDKAppID;
			this.im = TWebLive.createIM({
				SDKAppID
			});
			// 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
			this.im.on(TWebLive.EVENT.IM_READY, this.onReadyStateUpdate)
			// 被踢出
			this.im.on(TWebLive.EVENT.IM_KICKED_OUT, this.onKickedOut)
			// 收到自定义新消息
			this.im.on(TWebLive.EVENT.IM_CUSTOM_MESSAGE_RECEIVED, this.onCustomMessageReceived)
			// 收到文本新消息
			this.im.on(TWebLive.EVENT.IM_TEXT_MESSAGE_RECEIVED, this.onTextMessageReceived)
			// 加入直播间
			this.im.on(TWebLive.EVENT.IM_REMOTE_USER_JOIN, this.onRemoteUserJoin)
			// 离开直播间
			this.im.on(TWebLive.EVENT.IM_REMOTE_USER_LEAVE, this.onRemoteUserLeave)
			// 网络监测
			this.im.on(TWebLive.EVENT.IM_NET_STATE_CHANGED, this.onNetStateChanged)
			// 推流结束
			this.im.on(TWebLive.EVENT.IM_PUSH_STOPPED, this.onPushStopped)

			this.webLiveLogin();
		},
		// 没有昵称或者昵称为''或者""的，都用 userID 展示
		canIUseNick(nick) {
			if (nick && nick !== '""' && nick !== '\'\'') {
				return true
			}
			return false
		},
		// WEBLIVE 登录
		webLiveLogin() {
			this.im.login({
				userID: this.chatInfo.userID,
				userSig: this.chatInfo.userSig
			}).then(() => {
				//console.log('IM login成功')
			}).catch((err) => {
				console.log(err)
				this.$u.toast('IM 登录失败');
			})
		},
		imStopPush() {
			this.im.stopPush({
				roomID: this.chatInfo.groupId,
				postscript: '欢迎下次再来呦'
			});
			uni.redirectTo({
			    url: '/pagesA/live/liveEnd?roomid='+this.chatInfo.groupId
			});
		},
		// 直播开始推流和停止推流的通知
		ShowTips(content) {
			this.$u.toast(content);
		},
		onPushStopped(event) {
			this.$u.toast(event.data);
			uni.redirectTo({
			    url: '/pagesA/live/liveEnd?roomid='+this.chatInfo.groupId
			});
		},
		onTextMessageReceived({
			data: messageList
		}) {
			messageList.forEach((message) => {
				message.nickname = this.canIUseNick(message.nick) ? message.nick : message.from
				message.avatar = message.avatar
			})
			//console.log('onTextMessageReceived messageList', messageList)
			this.pushMsgList(messageList)
		},
		onCustomMessageReceived({
			data: messageList
		}) {
			//console.log('demo | custom message received', messageList);
			messageList.forEach((message) => {
				let type = message.payload.description;
				switch (type) {
					case 'send_gift':
						this.receivedGiftMsg(message);
					case 'send_like':
						this.receivedLikeMsg(message);
				}
			})
			//console.log('onCustomMessageReceived', messageList)
		},
		onRemoteUserJoin({
			data: messageList
		}) {
			let that = this;
			messageList.forEach((message) => {
				const userName = this.canIUseNick(message.nick) ? message.nick : message.from;
				message.payload.text = `欢迎 ${userName} 进入直播间`;
				message.type = 'Live-tips';
				that.$u.toast(message.payload.text);
			})
			console.log('onRemoteUserJoin', messageList);
			this.getOnlineUser('refresh');
		},
		onRemoteUserLeave({
			data: messageList
		}) {
			let that = this;
			messageList.forEach((message) => {
				const userName = this.canIUseNick(message.nick) ? message.nick : message.from;
				message.payload.text = `${userName} 离开了直播间`;
				message.type = 'Live-tips';
				that.$u.toast(message.payload.text);
			})
			console.log('onRemoteUserLeave', messageList);
			this.getOnlineUser('refresh');
		},
		onNetStateChanged() {},
		onError({
			data
		}) {
			if (data.message !== '' && data.message !== 'Network Error') {
				this.$u.toast(data.message);
			}
		},
		onReadyStateUpdate(event) {
			const isIMSDKReady = event.name === TWebLive.EVENT.IM_READY ? true : false
			this.isIMSDKReady = isIMSDKReady;
			if (isIMSDKReady) {
				console.log('IMSDKReady', 'IMSDKReady 已就绪')
				if (this.userRole === 'pusher') {
					//this.createRoom()
				} else {
					this.enterRoom()
				}
				this.setMyProfile()
				//this.getMyProfile()
			}
		},
		setMyProfile() {
			let nick = this.userInfo.nick_name;
			if (this.userRole == 'pusher') {
				nick = '主播'
			}
			this.im.setMyProfile({
					nick: nick,
					avatar: this.config.baseUrl + this.userInfo.headimgurl
				})
				.then(function(imResponse) {
					console.log('im | setMyProfile | success', imResponse);
				}).catch(function(imError) {
					console.warn('im | setMyProfile | failed', imError); // 设置资料失败的相关信息
				});
		},
		getMyProfile() {
			this.im.getMyProfile().then((res) => {
				this.userInfo.nickName = this.canIUseNick(res.data.nick) ? res.data.nick : this.userID,
					this.userInfo.avatar = res.data.avatar || this.userInfo.defaultImg
			}).catch(() => {})
		},
		// 加入直播间
		enterRoom() {
			this.im.enterRoom(this.chatInfo.groupId).then((imResponse) => {
				const status = imResponse.data.status
				if (status === TWebLive.TYPES.ENTER_ROOM_SUCCESS || status === TWebLive.TYPES
					.ALREADY_IN_ROOM) {
					//console.log(this.chatInfo.groupId, '成功加入直播间');
					if(this.userRole != 'pusher'){
						this.$u.post('live/api.live/enterRoom', {
							showLoading: false,
							roomid: this.chatInfo.groupId
						}).then(res => {
							this.getOnlineUser('refresh');
						});
					}
				}
			}).catch((imError) => {
				//this.$u.toast(imError)
				let content = imError.toString();
				uni.showModal({
					content: content
				})
			})
		},
		//退出直播间
		exitRoom() {
			let that = this;
			uni.showModal({
				content: '确定要退出直播间吗?',
				success(res) {
					if (res.confirm) {
						let promise = that.im.exitRoom(that.chatInfo.groupId);
						promise.then(function(imResponse) {
							// 退出直播间成功
							that.$u.post('live/api.live/exitRoom', {
								showLoading: false,
								roomid: that.chatInfo.groupId
							}).then(res => {});
							uni.reLaunch({
								url: '/'
							});
						}).catch(function(imError) {
							console.warn('im | exitRoom | failed', imError); // 退出直播间失败的相关信息
						});
					}
					
				}
			})
		},
		onLiveEnd() {
			this.$u.toast('直播已结束')
		},
		onKickedOut(event) {
			let msg = `${this.kickedOutReason(event.data.type)}被踢出，请重新登录。`
			this.$u.toast(msg);
			this.$app.goPage('/')
			window.location.reload()
		},
		imgError(item) {
			item.avatar = this.config.baseUrl + '/static/public/images/headimgurl.jpg';
		},
		kickedOutReason(type) {
			switch (type) {
				case this.TWebLive.TYPES.KICKED_OUT_MULT_ACCOUNT:
					return '由于多实例登录'
				case this.TWebLive.TYPES.KICKED_OUT_MULT_DEVICE:
					return '由于多设备登录'
				case this.TWebLive.TYPES.KICKED_OUT_USERSIG_EXPIRED:
					return '由于 userSig 过期'
				default:
					return ''
			}
		},
		handleMobileInputFocus() {
			window.scroll(0, 400)
			this.focus = true
		},
		handleMobileInputBlur() {},
		onScroll({
			target: {
				scrollTop
			}
		}) {
			let messageListNode = this.$refs['message-list']
			if (!messageListNode) {
				return
			}
			if (this.preScrollHeight - messageListNode.clientHeight - scrollTop < 20) {
				this.isShowScrollButtomTips = false
			}
		},
		// 如果滚到底部就保持在底部，否则提示是否要滚到底部
		keepMessageListOnButtom() {
			console.log('scroll bottom')
			let messageListNode = this.$refs['message-list']
			if (!messageListNode) {
				return
			}
			// 距离底部20px内强制滚到底部,否则提示有新消息
			if (this.preScrollHeight - messageListNode.clientHeight - messageListNode.scrollTop < 20) {
				this.$nextTick(() => {
					messageListNode.scrollTop = messageListNode.scrollHeight + 60
				})
				this.isShowScrollButtomTips = false
			} else {
				this.isShowScrollButtomTips = true
			}
			this.preScrollHeight = messageListNode.scrollHeight
		},
		reEditMessage(payload) {
			this.messageContent = payload
		},
		handleLine() {
			this.messageContent += '\n'
		},
		handleEnter() {
			this.sendTextMessage()
		},
		sendTextMessage(messageContent) {
			window.scroll(0, 0) //ios键盘回落
			if (messageContent === '' || messageContent.trim().length === 0) {
				this.$u.toast('不能发送空消息哦！')
				return
			}
			let message = {
				payload: {
					text: ''
				}
			}
			message.nickname = this.userRole == 'pusher' ? '主播' : this.userInfo.nick_name
			message.avatar = this.userInfo.headimgurl
			message.payload.text = messageContent
			message.type = 'TIMTextElem'
			message.status = 'unsend'
			message.to = this.chatInfo.groupId
			message.time = Date.now() / 1000
			let msg = message
			msg.nickname = '我'
			this.im.sendTextMessage({
					roomID: this.chatInfo.groupId,
					priority: TWebLive.TYPES.MSG_PRIORITY_NORMAL,
					text: messageContent
				})
				.then(() => {
					this.pushMsgList(msg)
				})
				.catch(error => {
					message.status = 'fail'
					//JSON.stringify(error, ['message', 'code'])
					if (error.code === 80001) {
						error.message = '消息中可能包含敏感词汇'
					}
					this.$u.toast(error.message)
				})
		},
		random(min, max) {
			return Math.floor(Math.random() * (max - min + 1) + min)
		},
		chooseEmoji(item) {
			this.messageContent += item
		},
		// 消息区分
		leaveMsg(type) {
			return type === 'Live-tips'
		},
		textMsg(type) {
			return type === 'TIMTextElem'
		},
		joinMsg(type) {
			return type === 'Live-tips'
		},
		customMsg(type) {
			return type === 'TIMCustomElem'
		},
		checkLogin() {
			this.messageContent = '';
			this.$u.toast('请先登录');
		},
		tabClick(index) {
			// window.scroll(0, 0)    //切换tab，聊天区域滑到底部
			this.isActive = ['', '']
			this.isActive[index] = 1
			this.tabSelected = index
		},
		pushMsgList(data) {
			if (Array.isArray(data)) {
				this.msgList = [...this.msgList, ...data]
			} else {
				this.msgList = [...this.msgList, data]
			}
		},
		pushCurrentTipsList(data) {
			let timer = null
			if (Array.isArray(data)) {
				this.currentLiveTips = [...this.currentLiveTips, ...data]
			} else {
				this.currentLiveTips = [...this.currentLiveTips, data]
			}
			timer = setTimeout(() => {
				this.currentLiveTips.shift()
			}, 2000)
			if (this.currentLiveTips.length === 0) {
				clearTimeout(timer)
			}
		},
		hideGiftAni() {
			this.hasGift = false;
			setTimeout(() => {
				this.showGiftAni();
			}, 1000)
		},
		receivedGiftMsg(msg) {
			let msgData = JSON.parse(JSON.parse(msg.payload.data));
			let gift_id = msgData.gift_id;
			let gift_num = msgData.gift_num;
			let sendUser = {
				nick_name: this.canIUseNick(msg.nick) ? msg.nick : msg.from,
				headimgurl: msg.avatar
			};
			this.pushGiftStack(gift_id, gift_num, sendUser);
			this.getOnlineUser('refresh');
		},
		pushGiftStack(gift_id, gift_num, sendUser){
			this.giftList.forEach(item => {
				if (item.id == gift_id) {
					let gift_info = item;
					gift_info.giftNum = gift_num;
					let gift_stack = [];
					gift_stack['giftInfo'] = gift_info;
					gift_stack['sendGiftUser'] = sendUser;
					this.giftStack.push(gift_stack);
					this.showGiftAni();
				}
			})
		},
		showGiftAni() {
			if(!this.hasGift){
				var msg = this.giftStack.shift()
				if (msg) {
					this.hasGift = true,
					this.giftInfo = msg.giftInfo,
					this.sendGiftUser = msg.sendGiftUser
				}
			}
		},
		sendGiftMsg(gift_id, gift_num) {
			let msgData = {
				gift_id: gift_id,
				gift_num: gift_num
			};
			let sendUser = {
				nick_name: this.canIUseNick(this.userInfo.nick_name) ? this.userInfo.nick_name : this.userInfo
					.user_id,
				headimgurl: this.config.baseUrl + this.userInfo.headimgurl
			};
			let that = this;
			this.sendCustomMessage(JSON.stringify(msgData), 'send_gift', function() {
				//console.log('callback sendGiftMsg');
				that.pushGiftStack(gift_id, gift_num, sendUser);
			});
		},
		sendCustomMessage(message, type, callback) {
			let promise = this.im.sendCustomMessage({
				roomID: this.chatInfo.groupId,
				priority: TWebLive.TYPES.MSG_PRIORITY_LOW, // 低优先级
				data: JSON.stringify(message), // 用于标识该消息是点赞类型的自定义消息
				description: type,
				extension: ''
			});
			promise.then(function(imResponse) {
				//console.log('im | sendCustomMessage | OK', imResponse);
				callback();
			}).catch(function(imError) {
				console.log('im | sendCustomMessage | failed', imError);
			});
		},
		getGift() {
			this.$u.get('live/api.live/getGiftList', {
					'showLoading': false
				})
				.then(res => {
					this.giftList = res.data.giftList;
				})
		},
		getOnlineUser(source = 'add') {
			if (source == 'refresh') {
				this.onlineUserLoadingType = 'more';
				this.p = 0;
			}
			if (this.onlineUserLoadingType == 'nomore') {
				return;
			}

			this.onlineUserLoadingType = 'loading';
			this.p++;
			this.$u.get('live/api.live/getOnlineUser?p=' + this.p + '&roomid=' + this.chatInfo.groupId, {
				'showLoading': false
			}).then(res => {
				if (this.p == 1) {
					this.onlineUser = res.data.onlineUser;
				} else {
					this.onlineUser = [...this.onlineUser, ...res.data.onlineUser];
				}
				//判断是否还有下一页，有是more  没有是nomore
				this.onlineUserLoadingType = this.p == res.data.pageCount ? 'nomore' : 'more';
				this.onlineUserNum = res.data.onlineUserNum;
			})
		},
		sendLikeMsg() {
			let that = this;
			this.sendCustomMessage({}, 'send_like', function() {
				let msgData = {
					nickname: '我',
					headimgurl: that.config.baseUrl + that.userInfo.headimgurl,
					payload:{
						text: '点赞了主播~~'
					},
					type: 'TIMTextElem'
				};
				that.pushMsgList(msgData)
				
			});
		},
		receivedLikeMsg(msg) {
			let msgData = {
				nickname: this.canIUseNick(msg.nick) ? msg.nick : msg.from,
				headimgurl: msg.avatar,
				payload:{
					text: '点赞了主播~~'
				},
				type: 'TIMTextElem'
			};
			this.getLike();
			this.pushMsgList(msgData);
		},
		getLike(gift_id, gift_num) {
			this.$u.post('live/api.live/getLike', {
				roomid: this.chatInfo.groupId,
				showLoading: false
			}).then(res => {
				this.likeNum = res.data.likeNum;
			})
			
		},

	}

}
